import { Component, OnInit } from '@angular/core';
import {Resources} from "../resources";
import {ActivatedRoute, Router} from "@angular/router";
import {ResourcesService} from "../resources.service";
import {ResponseUtil} from "../../../../util/response-util";
import {MsgResult} from "../../../../models/msg-result";
import {PageSubject} from "../../../../util/page-subject";
import {Dialog} from "../../../../widgets/one-dialog/dialog";
import {OneDialogService} from "../../../../widgets/one-dialog/one-dialog.service";
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {Path} from "../../../../portal/admin/admin-breadcrumb/breadcrumb";
import {MsgConstants} from "../../../../constants/constants";

@Component({
  selector: 'app-resource-add',
  templateUrl: './resource-add.component.html'
})
export class ResourceAddComponent implements OnInit {

  //声明实例
  resources :Resources;

  resourcesForm : FormGroup;

  constructor(
    private router : Router,
    private route : ActivatedRoute,
    private pageSubject : PageSubject,
    private resourcesService : ResourcesService,
    private dialogService : OneDialogService,
    private responseUtil : ResponseUtil,
    private fb: FormBuilder,
  ) {
      this.initObject();
  }
  ngOnInit() {
    this.pushPage();
  }

  /**
   * 面包屑导航
   */
  pushPage(){
    let path = new Path("权限系统","");
    this.pageSubject.pushPage("资源管理","添加",path);
  }

  //添加资源信息
  onSubmit(){
    this.resourcesService.insertResource(this.resourcesForm.value).subscribe(
      result=>this.responseUtil.success(result,this.processResult),
      message =>this.responseUtil.error(message)
    );
  }
  /**
   *  获取添加信息
   * @param json
   */
  private processResult = (result : MsgResult) => {
    if(result && result.code == MsgConstants.MSG_CODE_OK){
      this.dialogService.successWithCancelBtn("添加成功，是否继续添加？",()=>this.initObject(),()=>this.cancelResourceAdd());
    }
    if(result && result.code != MsgConstants.MSG_CODE_OK){
      this.dialogService.info(result.message);
    }
  }

  //取消添加保存
  cancelResourceAdd(){
    this.router.navigate(['..'],{relativeTo : this.route});
  }

  /**
   * 实例化对象
   */
  private initObject(){
    this.resources =new Resources("","","","","","0","0");
    this.buildForm();
  }
  /**
   * 构造表单
   */
  buildForm(): void {
    this.resourcesForm = this.fb.group({
      'id': [this.resources.id],
      'name': [this.resources.name,[
        Validators.required,
        Validators.maxLength(10)
      ]],
      'url': [this.resources.url,[
        Validators.required,
        Validators.maxLength(100)
      ]],
      'isValid': [this.resources.isValid],
      'isShow': [this.resources.isShow]
    });

    this.resourcesForm.valueChanges.subscribe(
      data => this.onValueChanged(data)
    );
    this.onValueChanged();
  }

  /**
   * 值变化监听
   * @param data
   */
  onValueChanged(data?: any) {
    if (!this.resourcesForm) {
      return;
    }
    const form = this.resourcesForm;
    for (const field in this.formErrors) {
      this.formErrors[field] = '';
      const control = form.get(field);
      if (control && control.dirty && !control.valid) {
        const messages = this.validationMessages[field];
        for (const key in control.errors) {
          this.formErrors[field] += messages[key] + ' ';
        }
      }
    }
  }

  /**
   * 校验字段
   * @type {{name: string; code: string}}
   */
  formErrors = {
    'name': '',
    'url': ''
  };
  /**
   * 校验提示信息
   * @type {{name: {required: string; maxlength: string}; code: {required: string; maxlength: string; pattern: string}}}
   */
  validationMessages = {
    'name': {
      'required': '名称不能为空',
      'maxlength': '长度不能超过10'
    },
    'url': {
      'required': 'URL不能为空',
      'maxlength': '长度不能超过100'
    }
  };

}
